
const {EquipmentModel, CabinetModel, EquipmentLogModel } = require('../../models/index')
const koaTool = require('../../commons/koa_tool')
const _const = require('../../commons/const')
const mqttService = require("../../services/mqtt")
class EquipmentController {

    // 消除设备响应缓存
    clearEquCacheData = async (ctx) => {
        let resultData = mqttService.clearCacheRelationData();
        koaTool.succ(ctx, true)
    }

    // 数据检验
    saveValid = async (ctx, input) =>{
        return new Promise(async resolve => {
            const {isNull} = require("../../commons/util.js");

            let validKeys = [
                {prop: "name", label: "设备名称"},
                {prop: "code", label: "设备编号"},
                {prop: "cordon", label: "警戒线"},
                {prop: "type", label: "设备类型"},
                {prop: "enterprise_id", label: "所属企业"},
                {prop: "cabinet_id", label: "所属储存柜"},
            ];
    
            let unValidIdx = validKeys.findIndex(item => {
                return isNull(input[item.prop])
            });
            if(unValidIdx != -1){
                koaTool.error(ctx,`${validKeys[unValidIdx].label}不能为空`);
                return resolve(false)
            }

            // 检查所属柜容量是否已满
            let cabinetEntity = await CabinetModel.findById(input.cabinet_id).lean();
            let coutQuery = {
                cabinet_id: input.cabinet_id, status: 1
            }
            if(input._id){
                coutQuery._id = { "$ne": input._id }
            }
            let equipmentCount = await EquipmentModel.countDocuments(coutQuery);
            console.log(cabinetEntity.volume, equipmentCount)
            if(equipmentCount >= cabinetEntity.volume ){
                koaTool.error(ctx,"所属柜中设备容量已满，请检查");
                return resolve(false)
            }
    
            // 设备code不能重复
            let existQuery = {
                code: input.code,
                status: 1
            };
            if(input._id){
                existQuery._id = {
                    "$ne": input._id,
                }
            }
            let existEntity = await EquipmentModel.findOne(existQuery);
            if(existEntity){
                koaTool.error(ctx,"设备编号已存在，请确认");
                return resolve(false)
            }

            return resolve(true);
        })

    }

    //新增
    create = async (ctx) => {

        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        // 数据检验
        let validRes = await this.saveValid(ctx,input)
        if(!validRes) return;


        let newData = Object.assign({}, input, {
            status: 1
        })

        let equipment = await EquipmentModel.create(newData)

        mqttService.getEquipmentData();
    
        return koaTool.success(ctx,'创建成功');
    }

    //详情
    detail = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        const {isNull} = require("../../commons/util.js");
        if(isNull(input.id)){
            return koaTool.error(ctx,"异常");
        }

        const detail = await EquipmentModel.findById(input.id)
        if(detail){
            return koaTool.success(ctx,'获取成功',{
                detail
            });
        }
        return koaTool.error(ctx,'无该类目信息');
    }
    //更新
    update = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        const {isNull} = require("../../commons/util.js");
        if(isNull(input.id)){
            return koaTool.error(ctx,"异常");
        }

        // 数据检验
        let validRes = await this.saveValid(ctx,input)
        if(!validRes) return;


        let detail = await EquipmentModel.findById(input.id)
        if (!detail) {
            return koaTool.error(ctx,"类目异常");
        }

        
        let props = ["name","code", "cordon",'type','gas_type',"enterprise_id","machine_status","cabinet_id","wafer_uid"];
        props.forEach(prop => {
            if(!isNull(input[prop])){
                detail[prop] = input[prop];
            }
        });

        await detail.save()
        mqttService.getEquipmentData();
        return koaTool.success(ctx, '编辑成功');
    }
    //删除
    delete = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['id'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        const {isNull} = require("../../commons/util.js");
        if(isNull(input.id)){
            return koaTool.error(ctx,"异常");
        }

        let detail = await EquipmentModel.findById(input.id)
        if (!detail) {
            return koaTool.error(ctx,"类目异常");
        }

        detail.status = 2;  //标记删除

        await detail.save();
        mqttService.getEquipmentData();
        return koaTool.success(ctx, '删除成功');
    }
    //列表
    list = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['page'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        let {
            page,
            limit,
            code,
        } = ctx.request.query;


        limit = Number(limit)
        page = page || 0
        page = page - 1
        let query = {
            status: 1,
        };


        if (code) {
            const reg = new RegExp(code, 'i') //不区分大小写
            query.$and = query.$and || []
            query.$and.push({
                $or: [
                    {'code': {$regex: reg}},
                ]
            })
        }

        ["enterprise_id","cabinet_id","type","machine_status"].forEach(prop => {
            if(ctx.request.query[prop]){
                query[prop] = ctx.request.query[prop]
            }
        })

        let total = await EquipmentModel.countDocuments(query)
        let list = await EquipmentModel.find(query)
                                    .populate({path: "enterprise_id",select: "name"})
                                    .populate({path: "cabinet_id", select: "name"})
                                    .sort([['create_at',-1]])
                                    .skip(page * limit)
                                    .limit(limit)
                                    .lean();
        let proArr = list.map(async item => {
            // 临时 兼容老数据无值的情况
            item.cabinet_id = item.cabinet_id || {};
            item.enterpriseName = item.enterprise_id.name;
            item.enterprise_id = item.enterprise_id._id;
            item.cabinetName = item.cabinet_id.name;
            item.cabinet_id = item.cabinet_id._id;
            item.typeName = _const.EQUIPMENT_TYPE_MAP[item.type],
            item.machineStatusName = _const.MACHINE_STATUS_MAP[item.machine_status];

            item.curReadNum = item.real_num;
            item.newRealDate = item.real_time;
            // let equipmentLog = await EquipmentLogModel.find({equipment_id: item._id}).sort({_id: -1}).limit(1);
            // if(equipmentLog && equipmentLog[0]){
            //     item.curReadNum = equipmentLog[0].real_num;
            //     item.newRealDate = equipmentLog[0].create_at
            // }
           
            return item;
        })

        await Promise.all(proArr);

        koaTool.succ(ctx, {
            list,
            total
        })
    }

    // 获取未接入系统的设备列表
    getUnRelationData = async (ctx) => {
        let resultData = mqttService.getUnRelationDataList();
        koaTool.succ(ctx, resultData)
    }

    // 根据企业ID和存储柜ID获取设备数据
    getEquDataByCabId = async (ctx) => {
        let { cabinetId = 1, enterpriseId } = ctx.request.query;
        if(!(cabinetId && enterpriseId)){
            return koaTool.error(ctx, "参数缺少，请检查");
        }
        
        let queryData = {
            enterprise_id: enterpriseId,
            cabinet_id: cabinetId, 
            machine_status: 1,
            status: 1
        }
        let resultData = await EquipmentModel.find(queryData).lean();
        koaTool.succ(ctx, resultData)
    }
    
    // 设备类型
    getEquipmentTypeList = async (ctx) => {
        const {EQUIPMENT_TYPE_LIST} = require('../../commons/const.js');
        return koaTool.success(ctx,"获取成功",{
            list: EQUIPMENT_TYPE_LIST
        })
    }

    // 气体类型
    getEquGasTypeMap = async (ctx) => {
        const {GAS_TYPE, map2List} = require('../../commons/const.js');
        return koaTool.success(ctx,"获取成功", {
            list: map2List(GAS_TYPE, false)
        })
    }

    // 设备状态
    getMachineStatusList = async (ctx) => {
        const {MACHINE_STATUS_LIST} = require('../../commons/const.js');
        return koaTool.success(ctx,"获取成功",{
            list: MACHINE_STATUS_LIST
        })
    }

}

module.exports=new EquipmentController()

